<template>
  <div class="nbtable">
    <fc-title title="决策表因子">
      <Feature
        @Listchange="onFeatureUpdate"
        @addFeature="(value) => addFeatures(value)"
        :selectedItems="selectedItems"
        :type="type"
      />
    </fc-title>
    <br />
    <fc-title title="决策表">
      <a-table
        class="ellipsis-header"
        :columns="hhead"
        :data-source="hdata"
        :pagination="false"
        bordered
        :scroll="{ y: 400 }"
        :customRow="customRow"
      >
        <template
          slot="name"
          slot-scope="text, record, scope, columnDef"
        >
          <editable-cell
            :text="text"
            :editStatus="editStatus"
            @change="onCellChange(record.key, scope, $event, text, columnDef)"
          />
        </template>
        <!-- <template slot="operation" slot-scope="text,record">
          <a-button type="link" @click="deleteRow(record)">删除</a-button>
        </template>-->
      </a-table>
    </fc-title>

    <a-modal
      v-model="addFeatureVisible"
      title="添加因子"
      :closable="true"
      @ok="handleOk"
    >
      <!-- <a-button @click="getAllFeatures">查询</a-button> -->
      <a-table
        :columns="featureColumn"
        :data-source="featureData"
        rowKey="featureCode"
        :pagination="false"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          getCheckboxProps,
        }"
      ></a-table>
    </a-modal>
    <div>行：{{ currentRow }}</div>
    <div>列：{{ currentCol }}</div>
    <div>行index：{{ currentRowIndex }}</div>
    <div>列index：{{ currentColIndex }}</div>
    <div>值：{{ currentValue }}</div>
    <div>行因子值：{{ currentRowValue }}</div>
    <div>列因子值：{{ currentColValue }}</div>
    <a-table
      :columns="columns"
      :dataSource="data"
      :customRow="customRow"
      :customHeaderRow="customHeaderRow"
      bordered
      ><template
        slot="name"
        slot-scope="text, record, index, column"
      >
        <div
          @click="clickCell(record, index, column)"
          :class="{ highlighted: currentColIndex === column.colIndex && currentRowIndex === index }"
        >
          <EditCellTest
            :text="text"
            @change="changeCell($event, record, index, column)"
          ></EditCellTest>
        </div>
      </template>
    </a-table>
    <a-space>
      <a-button
        @click="getTable"
        type="primary"
        >获取表结构</a-button
      >
      <a-button
        @click="getData"
        type="primary"
        >获取数据</a-button
      >
      <a-button
        @click="generate"
        type="primary"
        >生成表格</a-button
      >
      <a-button
        @click="merge"
        type="primary"
        >合并表头</a-button
      >
      <a-button
        @click="split"
        type="primary"
        >拆分表头</a-button
      >
    </a-space>
  </div>
</template>
<script>
import EditableCell from './EditableCell'
import FeatureItem from './FeatureItem'
import FeatureCombine from './FeatureCombine'
import DmtValue from './DmtValue'
import FcTitle from './FcTitle'
import Feature from './Feature'
import EditCellTest from './EditCellTest'
// import { getDmtModel, downloadTemplate, saveDmtModel, loadDmtModel, getFeatures } from '@/api/dmt'

const installColumnRender = (columDef) => {
  if (columDef.children != null && columDef.children.length > 0) {
    columDef.children.forEach((v) => {
      installColumnRender(v)
    })
  } else {
    columDef.scopedSlots = { customRender: 'name' }
  }
}

const featureColumn = [
  {
    title: 'Id',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '因子代码',
    dataIndex: 'featureCode',
    key: 'featureCode',
  },
  {
    title: '因子名称',
    dataIndex: 'featureName',
    key: 'featureName',
  },
  {
    title: '因子描述',
    dataIndex: 'desc',
    key: 'desc',
  },
]

import data from './data.json'
// import { find } from 'store/storages/all'
import { getFactorList, getFactorWithCode } from './api/ruleApi'
import { matchingTypeLabel } from './model/RuleFactorValue'
import { isArray } from 'fc-cli-core'

/**
 * 这里的2是当前这一列的分区大小
 * @param {*} value
 * @param {*} row
 * @param {*} index
 * @returns
 */
export default {
  components: {
    EditableCell,
    FeatureItem,
    FeatureCombine,
    DmtValue,
    FcTitle,
    Feature,
    EditCellTest,
  },
  created() {
    this.form = this.$form.createForm(this)
    this.featureData = getFactorList().map((item, index) => ({
      ...item,
      id: String(index + 1),
      featureCode: item.code,
      featureName: item.label,
    }))
  },
  computed: {
    uploadUrl: function () {
      const upload = 'http://localhost:4000/api/dmt/model/upload/' + this.model.code
      return upload
    },
  },
  data() {
    return {
      columns: [
        {
          dataIndex: 'sex',
          key: 'sex',
          title: 'sex',
          isRowHead: true,
          customRender: (value, record, index) => {
            return {
              children: value,
              attrs: {
                rowSpan: index % 2 === 0 ? 2 : 0,
              },
              style: {
                color: '#A00',
              },
            }
          },
        },
        {
          dataIndex: 'info',
          key: 'info',
          title: 'info',
          isRowHead: true,

          customRender: (value) => {
            return {
              children: value,
              // attrs: {
              //   rowSpan: 4,
              // },
              // style: {
              //   color: '#A00',
              // },
            }
          },
        },
        {
          title: 'name1',
          id: 'name1',
          dataIndex: 'name1',
          key: 'name1',
          headRowIndex: 0,
          // colSpan: 6,
          children: [
            {
              title: 'age1',
              id: 'age1',
              key: 'name1_age1',
              dataIndex: 'name1_age1',
              colTitle: 'name1_age1',
              scopedSlots: { customRender: 'name' },
              headRowIndex: 1,
              colIndex: 0,
              customCell: (text, index) => {
                const obj = {
                  style: {},
                  attrs: {},
                }

                //  if(index === 0){
                //   obj.attrs.colSpan=2
                // }

                // if(index % 2 === 0){
                //   obj.attrs.rowSpan=2
                // }else{
                //   obj.style={display:"none"}
                // }
                return obj
              },
            },
            {
              title: 'age2',
              id: 'age2',
              key: 'name1_age2',
              dataIndex: 'name1_age2',
              colTitle: 'name1_age2',
              scopedSlots: { customRender: 'name' },
              colIndex: 1,
              headRowIndex: 1,
              customCell: (text, index) => {
                const obj = {
                  style: {},
                  attrs: {},
                }
                // if(index === 0){
                //   obj.style={display:"none"}
                // }
                return obj
              },
            },
          ],
        },
        {
          title: 'name2',
          id: 'name2',
          dataIndex: 'name2',
          key: 'name2',
          headRowIndex: 0,
          children: [
            {
              title: 'age1',
              id: 'age1',
              key: 'name2_age1',
              dataIndex: 'name2_age1',
              colTitle: 'name2_age1',
              scopedSlots: { customRender: 'name' },
              colIndex: 2,
            },
            {
              title: 'age2',
              id: 'age2',
              key: 'name2_age2',
              dataIndex: 'name2_age2',
              colTitle: 'name2_age2',
              scopedSlots: { customRender: 'name' },
              colIndex: 3,
            },
          ],
        },
        {
          title: 'name3',
          id: 'name3',
          dataIndex: 'name3',
          key: 'name3',
          headRowIndex: 0,
          children: [
            {
              title: 'age1',
              id: 'age1',
              key: 'name3_age1',
              dataIndex: 'name3_age1',
              colTitle: 'name3_age1',
              scopedSlots: { customRender: 'name' },
              colIndex: 2,
            },
            {
              title: 'age2',
              id: 'age2',
              key: 'name3_age2',
              dataIndex: 'name3_age2',
              colTitle: 'name3_age2',
              scopedSlots: { customRender: 'name' },
              colIndex: 3,
            },
            {
              title: 'age3',
              id: 'age3',
              key: 'name3_age3',
              dataIndex: 'name3_age3',
              colTitle: 'name3_age3',
              scopedSlots: { customRender: 'name' },
              colIndex: 3,
            },
          ],
        },
      ],
      data: [
        {
          key: '1',
          name1_age1: '11111',
          name1_age2: '22222',
          name2_age1: '',
          name2_age2: '',
          sex: 'sex1',
          info: 'info1',
        },
        {
          key: '2',
          name1_age1: '33333',
          name1_age2: '44444',
          name2_age1: '',
          name2_age2: '',
          sex: 'sex1',
          info: 'info2',
        },
        {
          key: '3',
          name1_age1: '',
          name1_age2: '',
          name2_age1: '',
          name2_age2: '',
          sex: 'sex2',
          info: 'info1',
        },
        {
          key: '4',
          name1_age1: '',
          name1_age2: '',
          name2_age1: '',
          name2_age2: '',
          sex: 'sex2',
          info: 'info2',
        },
      ],
      matchingTypeLabel,
      createLoading: false,
      editStatus: false,
      dmtName: 'aaa',
      mem: 'ss',
      hhead: [],
      hdata: [],
      rowClassName: 'rowClassName',
      model: {},

      selectedKeys: [],
      filteredItems: [],
      disabled: false,

      addFeatureVisible: false,
      featureColumn: featureColumn,
      featureData: [],

      type: '',

      selectedRowKeys: [],
      selectedFeatures: [],

      selectedItems: [],

      param: {},

      dmtValues: [],

      colFactor: [
        {
          key: 'name',
          label: 'name',
          values: [
            {
              key: 'name1',
              code: 'name1',
              label: 'name1',
            },
            {
              key: 'name2',
              code: 'name2',
              label: 'name2',
            },
          ],
        },
        {
          key: 'age',
          label: 'age',
          values: [
            {
              key: 'age1',
              code: 'age1',
              label: 'age1',
            },
            {
              key: 'age2',
              code: 'age2',
              label: 'age2',
            },
          ],
        },
      ],
      rowFactor: [
        {
          key: 'sex',
          label: 'sex',
          values: [
            {
              key: 'sex1',
              code: 'sex1',
              label: 'sex1',
            },
            {
              key: 'sex2',
              code: 'sex2',
              label: 'sex2',
            },
          ],
        },
        {
          key: 'info',
          label: 'info',
          values: [
            {
              key: 'info1',
              code: 'info1',
              label: 'info1',
            },
            {
              key: 'info2',
              code: 'info2',
              label: 'info2',
            },
          ],
        },
      ],
      currentRow: '',
      currentCol: '',
      currentRowIndex: null,
      currentColIndex: null,
      currentValue: '',
      currentRowValue: '',
      currentColValue: '',
      mouseStatus: '',
      selectTableHead: [],
    }
  },
  methods: {
    onValueUpdate: function (values) {
      console.log('返回值模型数据:', values)
      this.dmtValues = values
    },

    // 去除因子名称，递归
    removeFeatureName: function (feature) {
      feature.forEach((item) => {
        if (item.children) {
          this.removeFeatureName(item.children)
        } else {
          item.title = item.title.split('/').pop()
        }
      })
    },
    // 生成行
    generateColumns(arrays, depth = 0, pre) {
      if (arrays.length === 0) {
        return [
          {
            title: '结果集',
            dataIndex: 'result',
            key: 'result',
            align: 'center',
            scopedSlots: { customRender: 'name' },
          },
        ]
      }
      if (depth >= arrays.length) {
        return []
      }
      const arr = getFactorWithCode(arrays[depth])
      return arr?.values.map((item) => {
        console.log('----', item, this.matchingTypeLabel)
        let title = `${item.label}(${this.matchingTypeLabel[item.matchingRule]})`
        let dataIndex = pre ? `${pre}_${item.code}` : `${item.code}`
        const children = this.generateColumns(arrays, depth + 1, dataIndex)

        if (children.length > 0) {
          return { title, children }
        }
        return {
          title,
          ellipsis: true,
          align: 'center',
          dataIndex,
          scopedSlots: { customRender: 'name' },
          customCell: (record, index, column) => {
            return {
              on: {
                click: () => {
                  console.log(record, index, column, 'index333333333333')
                },
              },
            }
          },
        }
      })
    },

    //正交生成列
    cartesianProduct(arr, index = 0, current = {}) {
      // 结果数组
      let result = []

      // 如果索引等于数组的长度，意味着已经处理完所有数组
      if (index === arr.length) {
        return [current]
      }

      // 遍历当前层级的数组
      arr[index].forEach((obj) => {
        // 对于数组中的每个对象，获取键和值
        const key = Object.keys(obj)[0]
        const value = obj[key]
        // 创建一个新的对象，包含之前的结果和当前的键值对
        const newCurrent = {
          ...current,
          [key]: `${value.label}(${this.matchingTypeLabel[value.matchingRule]})`,
          id: `ccn_${Math.random() * 100}`,
        }

        // 递归调用，处理下一个数组
        const nextResult = this.cartesianProduct(arr, index + 1, newCurrent)

        // 将结果合并到最终结果数组中
        result = result.concat(nextResult)
      })

      return result
    },

    /**
     * 自定义的列表头渲染器
     */

    getCheckboxProps(record) {
      if (this.type === 'row') {
        return {
          props: {
            ...record,
            disabled: !!this.param.rowFeature?.find((item) => item.id === record.featureCode), // Column configuration not to be checked
          },
        }
      } else {
        return {
          props: {
            ...record,
            disabled: !!this.param.colFeature?.find((item) => item.id === record.featureCode), // Column configuration not to be checked
          },
        }
      }
    },

    generateDmt() {
      this.hdata = []
      this.hhead = []
      console.log('pram', this.param)
      // let colValue = this.param.colFeature.map(item => item.values.map(item => item.label))
      let colValue = this.param.colFeature.map((item) => item.id)

      let rowValue = this.param.rowFeature.map((item) => {
        const key = item.id
        return item.values.map((item) => ({ [key]: item }))
      })

      if (!colValue.length && !rowValue.length) return

      colValue = !colValue.length && rowValue.length ? [] : colValue
      console.log('rowValue', colValue, rowValue)

      const rowId = this.param.rowFeature.map((item) => item.id)
      const rowName = this.param.rowFeature.map((item) => ({ [item.id]: item.name })).reverse()

      const hhead = this.generateColumns(colValue)
      this.hhead = hhead ?? []
      console.log('hhead', hhead)
      let data1 = this.cartesianProduct(rowValue)
      // data1.forEach(item => {
      //   const fatorKeys = Object.keys(item)
      //   fatorKeys.forEach(key => {
      //     const fator = getFactorWithCode(key)
      //     if (fator) {
      //       fatorKeys[key] = `${fatorKeys[key]}(${this.matchingTypeLabel(fator.data)})`
      //     }
      //   })
      // })
      console.log('data1', data1)
      rowName.forEach((item) => {
        // 在数组第一行添加
        this.hhead.unshift({
          title: Object.values(item)[0],
          dataIndex: Object.keys(item)[0],
          key: Object.keys(item)[0],
          ellipsis: true,
          width: 120,
          align: 'center',
          // fixed: 'left',
          customRender: (value, record, index) => {
            const splitValue = value.split('(')[0]
            const findIndex = rowId.findIndex((item) => getFactorWithCode(item).values.find((item) => item.label === splitValue))
            let key = '',
              rowLen = 1
            if (findIndex + 1 < rowId.length) {
              key = rowId.filter((_, index) => index > findIndex)
            }
            if (key) {
              key.forEach((item) => {
                const datas = getFactorWithCode(item).values
                const len = datas.length
                rowLen = rowLen * len
              })
            }
            if (find && index % rowLen === 0) {
              return {
                children: value,
                attrs: {
                  rowSpan: rowLen,
                },
                style: {
                  color: '#A00',
                },
              }
            } else {
              return {
                children: value,
                attrs: {
                  rowSpan: 0,
                },
                style: {
                  color: '#A00',
                },
              }
            }
          },
        })
      })
      // this.hhead.push({
      //   title: '操作',
      //   dataIndex: 'operation',
      //   key: 'operation',
      //   fixed: 'right',
      //   align: 'center',
      //   width: 100,
      //   scopedSlots: { customRender: 'operation' }
      // })
      this.hdata = data1
      console.log('hhead:', this.hhead)
    },

    // 删除表格数据
    deleteRow(record) {
      console.log('record:', record)
      this.hdata = this.hdata.filter((item) => item.id !== record.id)
      console.log('this.hdata:', this.hdata)
      if (!this.hdata.length) {
        this.type = 'clear'
      }
    },

    // 跟新因子
    onFeatureUpdate: function (param) {
      param.name = ''
      console.log('因子组合发生变化:', param)
      this.param = param
      this.generateDmt()
    },

    getAllFeatures: function () {
      // console.log(getFactorList())
      // getFeatures().then(response => {
      //   console.log('response', response)
      //   this.featureData = response
      //   console.log('fe', this.featureData)
      // })
      this.featureData = getFactorList().map((item, index) => ({
        ...item,
        id: String(index + 1),
        featureCode: item.code,
        featureName: item.label,
      }))
    },

    onSelectChange(selected) {
      console.log('selectedRowKeys changed:', selected)
      this.selectedRowKeys = selected
    },

    addFeatures(value) {
      this.addFeature(value)
    },

    addFeature: function (value) {
      this.addFeatureVisible = true
      this.getAllFeatures()
      this.type = value
      if (Object.keys(this.param).length === 0) return
      console.log('proar', this.type, this.param)
      if (value === 'row') {
        this.selectedRowKeys = Array.from(new Set([...this.param.rowFeature.map((item) => item.id), ...this.param.colFeature.map((item) => item.id)]))
        console.log('====', this.selectedRowKeys)
      } else {
        this.selectedRowKeys = Array.from(new Set([...this.param.colFeature.map((item) => item.id), ...this.param.rowFeature.map((item) => item.id)]))
        console.log('====', this.selectedRowKeys)
      }
    },
    handleOk: function (e) {
      this.addFeatureVisible = false
      this.selectedFeatures = []
      console.log('selectedRowKeys', this.selectedRowKeys, this.type, this.param)
      this.selectedRowKeys.forEach((v) => {
        let value = this.featureData.find((item) => item.featureCode === v)
        if (this.type === 'row' && !this.param.rowFeature?.find((e) => e.id === v)) {
          this.selectedFeatures.push(value)
        } else if (this.type === 'col' && !this.param.colFeature?.find((e) => e.id === v)) {
          this.selectedFeatures.push(value)
        } else if (Object.keys(this.param).length === 0) {
          this.selectedFeatures.push(value)
        }
      })
      console.log('++++', getFactorWithCode('A1004'))
      this.selectedItems = this.selectedFeatures.map((v) => {
        return {
          id: v.featureCode,
          name: v.featureName,
          values: v.values,
        }
      })

      console.log('选中的因子:', this.selectedFeatures)
    },
    handleDisable(disabled) {
      this.disabled = disabled
    },
    customHeaderRow(column, index) {
      return {
        class: 'myClass',
        on: {
          mousedown: (e) => {
            console.log(column, index, 'column')
            console.log(e.column, 'dataset')
            this.mouseStatus = 'mousedown'
            this.selectTableHead = []
            //表头背景色清空/选中
            if (e.target.tagName === 'TH') {
              console.log(e.currentTarget.parentNode.querySelectorAll('th'), 'th')
              e.currentTarget.parentNode.querySelectorAll('th').forEach((item) => {
                item.style.backgroundColor = '#fafafa'
              })
              const column = this.findColByDataIndex(this.columns, e.target.getAttribute('key'))
              console.log(column, 'column')
              if (!column.isRowHead) {
                e.target.getAttribute('key')
                e.target.style.userSelect = 'none'
                e.target.style.backgroundColor = '#91cbfb'
                e.target.style.cursor = 'crosshair'
                this.selectTableHead.push(e.target.getAttribute('key'))
              }
            }
          },
          mousemove: (e) => {
            if (e.target.tagName === 'TH' && this.mouseStatus === 'mousedown') {
              e.target.style.userSelect = 'none'
              //根据mousedown鼠标位置计算选中区域
              const start = this.selectTableHead[0]
              const end = e.target.getAttribute('key')
              if (!(start && end)) {
                return
              }
              const selectDataIndex = this.findAllDataIndexes(this.columns, start, end)
              e.currentTarget.parentNode.querySelectorAll('th').forEach((item) => {
                if (selectDataIndex.includes(item.getAttribute('key'))) {
                  item.style.backgroundColor = '#91cbfb'
                } else {
                  item.style.backgroundColor = '#fafafa'
                }
              })
              e.target.style.cursor = 'crosshair'
              this.selectTableHead = selectDataIndex
              console.log(this.selectTableHead, 'selectTableHeadd')
            }
          },
          mouseup: (e) => {
            this.mouseStatus = 'mouseup'
            e.currentTarget.parentNode.querySelectorAll('th').forEach((item) => {
              item.style.cursor = 'default'
            })
          },
        },
      }
    },
    //根据鼠标点击和滑动区域，判断高亮区域的dataIndex
    findAllDataIndexes(columns, start, end) {
      let startIndex = 0
      let endIndex = 0
      let isStart = false
      let isEnd = false
      let selectDataIndex = []
      columns.forEach((item, index) => {
        if (isArray(item.children) && item.children.length) {
          selectDataIndex = selectDataIndex.concat(this.findAllDataIndexes(item.children, start, end))
        }
        if (item.dataIndex === start) {
          startIndex = index
          isStart = true
          selectDataIndex.push(item.dataIndex)
        }
        if (item.dataIndex === end) {
          endIndex = index
          isEnd = true
          selectDataIndex.push(item.dataIndex)
        }
        if (isStart && index > startIndex && !isEnd) {
          selectDataIndex.push(item.dataIndex)
        }
      })
      return selectDataIndex
    },
    selectAllHead(selectTableHead) {
      console.log(selectTableHead, 'selectTableHead')
    },
    customRow(record, index) {
      return {
        on: {
          // click: (event) => {
          //   console.log(this.currentColIndex, 'currentColIndex')
          //   if (!record.isRowHead) {
          //     event.currentTarget.parentNode.querySelectorAll('tr').forEach((item) => {
          //       item.childNodes.forEach((item) => {
          //         if (item?.style) {
          //           item.style.border = '1px solid #e8e8e8'
          //         }
          //       })
          //     })
          //     const node = this.findParentNode(event.target)
          //     for (let i = 0; i < node.parentNode.children.length; i++) {}
          //     if (node?.style) {
          //       node.style.border = '2px solid #2C78EB'
          //     }
          //   }
          // },
        },
      }
    },
    //高亮api
    highLightCell(rowIndex, colIndex, tableElement) {
      // console.log(tableElement.$el.currentTarget.querySelectorAll('tr'),'trtrtrtrtrt')
    },
    //循环找元素
    findParentNode(node) {
      if (node.tagName === 'TD') {
        return node
      } else {
        return this.findParentNode(node.parentNode)
      }
    },
    /**
     * 决策表上编辑的值更新到模型上.
     */
    onCellChange: function (index, rowIndex, newValue, oldValue, columnDef) {
      console.log('====', index, rowIndex, newValue, oldValue, columnDef)
      const column = columnDef.dataIndex
      this.hdata[rowIndex][column] = newValue
      this.currentValue = newValue
    },
    clickCell(record, index, column) {
      console.log(record, column, 'record column')
      this.currentRow = this.findRowTitle(record, this.columns)
      this.currentCol = this.findColTitle(column)
      this.currentRowIndex = index
      this.currentColIndex = column.colIndex
      this.currentValue = record[column.dataIndex]
      this.currentRowValue = this.findRow(record, this.columns)
      this.currentColValue = this.findCol(column, this.data)
    },
    findRowTitle(record, columns) {
      let rowTitle = ''
      columns.forEach((item) => {
        if (item.isRowHead) {
          for (let key in record) {
            if (key === item.dataIndex) {
              rowTitle += record[key] + '_'
            }
          }
        }
      })
      return rowTitle.slice(0, -1)
    },
    findColTitle(column) {
      return column.colTitle
    },
    findRow(record, columns) {
      const keysToRemove = columns.filter((condition) => condition.isRowHead).map((condition) => condition.dataIndex)
      const filteredKeys = Object.keys(record).filter((key) => !keysToRemove.includes(key))
      return filteredKeys.reduce((result, key) => {
        result[key] = record[key]
        return result
      }, {})
    },
    findCol(column, data) {
      const col = []
      data.forEach((item) => {
        col.push(item[column.dataIndex])
      })
      return col
    },
    getTable() {
      console.log(this.columns, 'columns')
    },
    getData() {
      console.log(this.data, 'data')
    },
    generate() {
      const { rowFactor, colFactor } = this
      this.columns = this.generateTable(rowFactor, colFactor).columns
      this.data = this.generateTable(rowFactor, colFactor).data
    },
    merge() {
      this.mergeHead(this.columns, this.selectTableHead, 'col')
    },
    split() {
      this.splitHead(this.columns, this.selectTableHead, 'col')
    },
    /*根据行列因子生成表格数据api
     *rowFactor行因子-[]
     *colFactor列因子-[]
     *isAuto是否自动生成-true/false
     *return {columns,data}-{}
     */
    generateTable(rowFactor, colFactor, isAuto) {
      let colValue = colFactor.map((item) => item.key)
      let rowValue = rowFactor.map((item) => {
        const key = item.key
        return item.values.map((item) => ({ [key]: item }))
      })
      if (!colValue.length && !rowValue.length) return

      colValue = !colValue.length && rowValue.length ? [] : colValue
      let columns = this.generateTableColumns(colFactor)
      const rowName = rowFactor.map((item) => ({ [item.key]: item.label })).reverse()
      const rowReserve = [...rowFactor].reverse()
      rowName.forEach((item, i) => {
        // 在数组第一行添加
        columns.unshift({
          title: Object.values(item)[0],
          dataIndex: Object.keys(item)[0],
          key: Object.keys(item)[0],
          ellipsis: true,
          width: 120,
          align: 'center',
          isRowHead: true,
          customRender: (value, record, index) => {
            const rowLen = i >= 1 ? rowReserve[i - 1]?.values.length * i : 1
            if (index % rowLen === 0) {
              return {
                children: value,
                attrs: {
                  rowSpan: rowLen,
                },
                style: {
                  color: '#A00',
                },
              }
            } else {
              return {
                children: value,
                attrs: {
                  rowSpan: 0,
                },
                style: {
                  color: '#A00',
                },
              }
            }
          },
        })
      })
      let data = this.generateTableRows(rowValue)
      return { columns, data }
    },
    /*合并表头api
     *columns:表头配置项-[]
     *mergeDataIndexs:需要合并表头的项-['name1','name2']
     *type:横向表头col合并还是纵向表头row合并-row/col
     */
    mergeHead(columns = [], mergeDataIndexs = [], type = 'col') {
      if (type === 'col') {
        const firstCol = mergeDataIndexs[0]
        const otherColList = mergeDataIndexs.slice(1)
        const firstObj = this.findColByDataIndex(columns, firstCol)
        let firstColNum = 0
        otherColList.forEach((item) => {
          const otherObj = this.findColByDataIndex(columns, item)
          this.$set(otherObj, 'colSpan', otherObj.children ? 0 - otherObj.children.length : 0)
          firstColNum += otherObj.children ? otherObj.children.length : 0
        })
        if (firstCol) {
          this.$set(firstObj, 'colSpan', firstObj.children ? firstColNum : mergeDataIndexs.length)
          firstObj.mergeDataIndexs = mergeDataIndexs
        }
      }
    },
    /*拆分表头api
     *colmns:表头配置项-[]
     *splitDataIndexs:需要拆分表头的项-['name1']
     *type:横向表头col拆分还是纵向表头row拆分-row/col
     */
    splitHead(columns = [], splitDataIndexs = [], type = 'col') {
      if ((type = 'col')) {
        splitDataIndexs.forEach((item) => {
          const obj = this.findColByDataIndex(columns, item)
          if (obj.mergeDataIndexs) {
            obj.mergeDataIndexs.forEach((mergeItem) => {
              const mergeObj = this.findColByDataIndex(columns, mergeItem)
              if (mergeObj) this.$set(mergeObj, 'colSpan', null)
            })
          }
        })
      }
    },
    //递归生成表格columns
    generateTableColumns(colFactor, depth = 0, preDataIndex, preIndex) {
      if (colFactor.length === 0) {
        return [
          {
            title: '结果集',
            dataIndex: 'result',
            key: 'result',
            align: 'center',
            scopedSlots: { customRender: 'name' },
          },
        ]
      }
      if (depth >= colFactor.length) {
        return []
      }
      return colFactor[depth]?.values.map((item, index) => {
        let title = `${item.label}`
        let dataIndex = preDataIndex ? `${preDataIndex}_${item.key}` : `${item.key}`
        const children = this.generateTableColumns(colFactor, depth + 1, dataIndex, index)
        if (children.length > 0) {
          return { title, id: item.id, dataIndex, key: dataIndex, headRowIndex: depth, children }
        }
        return {
          title,
          dataIndex,
          colIndex: depth === colFactor.length - 1 ? preIndex * colFactor.length + index : null,
          colTitle: dataIndex,
          key: dataIndex,
          headRowIndex: depth,
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'name' },
        }
      })
    },
    //生成表格row表头
    generateTableRows(arr, index = 0, current = {}) {
      // 结果数组
      let result = []

      // 如果索引等于数组的长度，意味着已经处理完所有数组
      if (index === arr.length) {
        return [current]
      }

      // 遍历当前层级的数组
      arr[index].forEach((obj, i) => {
        // 对于数组中的每个对象，获取键和值
        const key = Object.keys(obj)[0]
        const value = obj[key]
        // 创建一个新的对象，包含之前的结果和当前的键值对
        const newCurrent = {
          ...current,
          [key]: `${value.label}`,
          key: `key_${Math.random() * 100}`,
        }

        // 递归调用，处理下一个数组
        const nextResult = this.generateTableRows(arr, index + 1, newCurrent)

        // 将结果合并到最终结果数组中
        result = result.concat(nextResult)
      })
      console.log(result, 'reslut')
      return result
    },
    //递归遍历寻找columns节点
    findColByDataIndex(columns, dataIndex) {
      let obj = null
      columns.forEach((item) => {
        if (item.dataIndex === dataIndex) {
          obj = item
          return
        }
        if (!obj && item.children) {
          obj = this.findColByDataIndex(item.children, dataIndex)
          return
        }
      })
      return obj
    },
    changeCell(newValue, record, rowIndex, column) {
      if (isArray(column.mergeDataIndexs)) {
        column.mergeDataIndexs.forEach((item) => {
          this.data[rowIndex][item] = newValue
        })
      } else {
        this.data[rowIndex][column.dataIndex] = newValue
      }
      this.currentValue = newValue
      this.currentRowValue = this.findRow(record, this.columns)
      this.currentColValue = this.findCol(column, this.data)
    },
    handleChange: function () {
      console.log('handle change happend.')
    },

    loadModelData: function () {
      this.hdata = []
      this.hhead = []

      const code = this.model.code
      if (!code) {
        return
      }

      loadDmtModel(code).then((response) => {
        const data = response.model
        const meta = response.meta
        const head = response.head

        this.model = response

        this.hdata = data
        this.hdata.forEach((record) => {
          record.meta = meta
        })

        head.forEach((h) => {
          if (h.cardinal) {
            h.customRender = this.columnHeadRender
          } else {
            installColumnRender(h)
          }
        })

        this.hhead = head
      })
    },

    /**
     * 这样做的性能是有问题的，需要重构优化
     */
    saveModelData: function () {
      if (this.hdata.length === 0) {
        return
      }

      const strData = JSON.stringify(this.model)

      const deepCopy = JSON.parse(strData)

      deepCopy.model.forEach((v) => {
        delete v['meta']
      })

      saveDmtModel(deepCopy).then((response) => {
        if (!this.model.mode) {
          this.model.code = response.code

          const h = this.$createElement
          this.$info({
            title: '提示消息',
            content: h('div', {}, [h('p', '模型保存成功.')]),
            onOk() {},
          })
        }
      })
    },

    downloadTemplate: function () {
      this.editStatus = !this.editStatus
    },
    compont() {
      this.editStatus = false
    },

    // getDynamicModel: function () {
    //   const param = this.buildModel()

    //   if (!param) {
    //     return
    //   }

    //   this.hdata = []
    //   this.hhead = []

    //   getDmtModel(param).then(response => {
    //     const data = response.model
    //     const meta = response.meta
    //     const head = response.head

    //     this.model = response

    //     this.hdata = data
    //     this.hdata.forEach(record => {
    //       record.meta = meta
    //     })

    //     head.forEach(h => {
    //       if (h.cardinal) {
    //         h.customRender = this.columnHeadRender
    //       } else {
    //         installColumnRender(h)
    //       }
    //     })

    //     this.hhead = head
    //   })
    // }
  },
  mounted() {},
}
</script>

<style scoped lang='less'>
/** 这里的这时的颜色样式为什么会不生效，字体可以生效。 */
.mclass {
  color: blue;
  background-color: blueviolet;
}

::v-deep .ant-table-thead > tr > th {
  padding: 5px 5px;
}
::v-deep .ant-table-tbody > tr > td {
  padding: 0;
}

::v-deep .ant-table-row-hover > td {
  background-color: red;
  color: green;
}

/* 实现样式穿透 */
::v-deep .ant-table-tbody > tr.ant-table-row:hover > td {
  background: none !important;
}
::v-deep .ant-table-align-center {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.highlighted {
  outline: 1px solid #2c78eb;
}

.myClass::selection {
  background: transparent;
  color: rgba(0, 0, 0, 0.85);
}
</style>
